<!--
 * @Author: WLang
 * @LastEditors: WLang
 * @Description: 
 * @Date: 2023-06-30 15:43:46
 * @LastEditTime: 2023-07-19 17:18:43
 * @FilePath: \myblog\src\components\base\BaseForm.vue
-->
<template>
  <div>
    <el-form :model="form" v-if="formData" ref="elForm">
      <el-form-item v-for="(formItem, idx) in formData" :rules="validates[formItem.query]" :label="formItem.label" :prop="formItem.query" label-width="100px" :key="idx">
        <el-upload ref="uploadAvatar" v-if="formItem.type === 'image'"
  class="avatar-uploader"
  :action="userFileAction"
  :headers="{
      'Authorization': `Bearer ${$store.state.token}`,
    }"
  :show-file-list="false"
  :on-success="handleAvatarSuccess"
  :before-upload="beforeAvatarUpload"
  :on-error="beforeAvatarError">
  <el-image :src="userAvatarSrc" style="width:100px;hieght:100px">
  </el-image>
</el-upload>
        <el-input v-if="formItem.type !== 'image'" v-model="form[formItem['query']]" :type="formItem.type" :name="formItem.query" :placeholder="formItem.placeholder" :disabled="formItem.readonly" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import FORM_DATA from '@/config/form.config'
import VALIDATE_DATA from '@/config/validate.config'
export default {
  components:{},
  data(){
    return {
      form: {},
    }
  },
  props: {
    type: {
      type: String
    }
  },
created(){
  //筛选userInfo的form字段
  if (this.type === 'userInfo')
  {
    this.form = Object.fromEntries(Object.entries(this.$store.getters.userInfo).
    filter(([key])=> {
      return FORM_DATA['userInfo'].find(item => {
        return key == item['query']
      })
    }))
  }
},
mounted(){},
watch:{
  type() {
    this.initForm();
  }
},
computed:{
  userFileAction() {
    return process.env.VUE_APP_USER_UPLOAD_PATH
  },
  formData() {
    return FORM_DATA[this.type]
  },
  validates() {
    return VALIDATE_DATA
  },
  userAvatarSrc() {
    return this.form.avatar
  }
},
methods:{
  initForm() {
    //重置表单字段
    this.form = {};
    this.$refs['elForm'].resetFields();
  },
  handleAvatarSuccess(res) {
    this.form.avatar = res.data.fileURL;
  },
  //上传前限制文件大小和文件类型
  beforeAvatarUpload(file) {
    let {size, type} = file
    if (!/image/g.test(type))
    {
      this.$notify.error({
      title: '上传失败',
      message: '请上传图片类型文件'
    })
    this.$refs.uploadAvatar[0].abort(file)
    return false
    }
    if (size > 5 * 1024 * 1024)
    {
      this.$notify.error({
      title: '上传失败',
      message: '文件大小错误，不得超过5M'
    })
    this.$refs.uploadAvatar[0].abort(file)
    return false
    }
  },
  beforeAvatarError(err) {
    this.$notify.error({
      title: '上传失败',
      message: err.message.message
    })
  }
},
}
</script>
<style  scoped>
</style>